package cn.xiaopengstack.domain.strategy.service.rule.filter;

import cn.xiaopengstack.domain.strategy.model.entity.RuleActionEntity;
import cn.xiaopengstack.domain.strategy.model.entity.RuleMatterEntity;
import cn.xiaopengstack.domain.strategy.model.entity.StrategyRuleEntity;
import cn.xiaopengstack.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.xiaopengstack.domain.strategy.repository.IStrategyRepository;
import cn.xiaopengstack.domain.strategy.service.annotation.LogicStrategy;
import cn.xiaopengstack.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import cn.xiaopengstack.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author jiangyangang
 */
@Service
@Slf4j
@LogicStrategy(DefaultLogicFactory.LogicModel.RULE_BLACKLIST)
public class RuleBlackListLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity>{

    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> doFilter(RuleMatterEntity ruleActionEntity) {
        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRule(ruleActionEntity.getStrategyId(), DefaultLogicFactory.LogicModel.RULE_BLACKLIST.getCode());
        if (Objects.isNull(strategyRuleEntity)) {
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder().build();
        }
        String ruleValue = strategyRepository.queryStrategyRuleValue(ruleActionEntity.getStrategyId(), null, ruleActionEntity.getRuleModel());
        // 解析
        String[] ruleModelSplit = ruleValue.split(Constants.COLON);
        Integer awardId = Integer.valueOf(ruleModelSplit[0]);

        // 判断用户是否在黑名单内
        String[] blackUsers = ruleModelSplit[1].split(Constants.SPLIT);
        for (String userId : blackUsers) {
            if (userId.equals(ruleActionEntity.getUser().getUserId())) {
                return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                        .ruleModel(DefaultLogicFactory.LogicModel.RULE_BLACKLIST.getCode())
                        .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                        .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                        .data(RuleActionEntity.RaffleBeforeEntity.builder()
                                .awardId(awardId)
                                .strategyId(ruleActionEntity.getStrategyId())
                                .build())
                        .build();
            }
        }

        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();
    }
}
